package com.hospital.controller.admin;

import com.google.gson.Gson;
import com.hospital.dao.WardStatusDao;
import com.hospital.dao.impl.WardStatusDaoImpl;
import com.hospital.model.WardStatusView;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

/**
 * 病房管理Servlet
 * 处理管理员对病房信息的查询请求，支持按科室ID筛选或查看所有病房
 */
@WebServlet("/admin/wards")
public class WardManageServlet extends HttpServlet {
    /** 病房状态数据访问对象，用于查询病房状态信息 */
    private WardStatusDao wardStatusDao = new WardStatusDaoImpl();
    /** JSON转换工具对象，用于处理JSON数据的序列化和反序列化 */
    private Gson gson = new Gson();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
            throws ServletException, IOException {
        
        resp.setContentType("application/json;charset=UTF-8");
        
        try {
            String deptIdStr = req.getParameter("deptId");
            List<WardStatusView> wards;
            
            if (deptIdStr != null && !deptIdStr.trim().isEmpty()) {
                int deptId = Integer.parseInt(deptIdStr);
                wards = wardStatusDao.findByDeptId(deptId);
            } else {
                wards = wardStatusDao.findAll();
            }
            
            resp.getWriter().write(gson.toJson(wards));
            
        } catch (SQLException e) {
            resp.setStatus(500);
            resp.getWriter().write("{\"error\": \"数据库错误：" + e.getMessage() + "\"}");
            e.printStackTrace();
        } catch (NumberFormatException e) {
            resp.setStatus(400);
            resp.getWriter().write("{\"error\": \"无效的科室ID\"}");
        }
    }
} 